﻿namespace MicroCloud.Utils
{
    /// <summary>
    /// Stream扩展方法
    /// </summary>
    public static class StreamExtensions
    {
        /// <summary>
        /// 将 <see cref="Stream"/> 转换为 <see cref="string"/>
        /// </summary>
        /// <param name="stream">流</param>
        /// <param name="encoding">编码</param>
        /// <returns></returns>
        public static string ReadToString(this Stream stream, Encoding encoding = null)
        {
            encoding ??= Encoding.UTF8;
            using StreamReader reader = new(stream, encoding);
            return reader.ReadToEnd();
        }

        /// <summary>
        /// 将 <see cref="Stream"/> 转换成字节
        /// </summary>
        /// <param name="stream">流</param>
        /// <returns>字节</returns>
        public static byte[] ToBytes(this Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin); // 设置当前流的位置为流的开始

            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);

            stream.Seek(0, SeekOrigin.Begin);   // 设置当前流的位置为流的开始

            return bytes;
        }

        /// <summary>
        /// 将 <see cref="Stream"/> 转换为 Base64 字符串
        /// </summary>
        /// <param name="stream">流</param>
        /// <returns>Base64字符串</returns>
        public static string ToBase64String(this Stream stream)
        {
            return stream.ToBytes().ToBase64String();
        }

        /// <summary>
        /// 将 <see cref="MemoryStream"/> 转换成字节
        /// </summary>
        /// <param name="stream">内存流</param>
        /// <returns>字节</returns>
        public static byte[] ToBytes(this MemoryStream stream)
        {
            byte[] bytes = stream.ToArray();
            return bytes;
        }

        /// <summary>
        /// 将 <see cref="MemoryStream"/> 转换为 Base64 字符串
        /// </summary>
        /// <param name="stream">内存流</param>
        /// <returns>Base64字符串</returns>
        public static string ToBase64String(this MemoryStream stream)
        {
            byte[] bytes = stream.ToBytes();
            return bytes.ToBase64String();
        }

    }
}